<script setup>
import { ref } from 'vue'
import { userUpdate, userAdd } from '@/apis/index.js'

const show = ref(true)
const emit = defineEmits(['close', 'updata'])

// 父组件传过来的值
const props = defineProps(['formData'])

const form = ref({ ...props.formData })
// 验证规则
const rules = ref({
  roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
  description: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
})

// 获取ref,对应form 表单定义的ref
const ruleFormRef = ref()
// 提交表单
const submitForm = (formEl) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (!valid) return
    const { id, status } = form.value
    const parame = {
      ...form.value,
      status: status ? 0 : 1,
    }
    // 有id 则是编辑
    if (id) {
      await userUpdate(parame)
    } else {
      // 没有则是新增
      await userAdd(parame)
    }
    emit('updata')
    emit('close')
  })
}

// 取消
const changeClose = () => {
  // 发出时间，让父组件关闭弹框
  emit('close')
}
</script>

<template>
  <el-dialog v-model="show" title="温馨提示" width="40%" @close="changeClose">
    <el-form ref="ruleFormRef" :model="form" label-width="120px" :rules="rules">
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="form.roleName" placeholder="请输入角色名称" />
      </el-form-item>
      <el-form-item label="角色描述" prop="description">
        <el-input
          v-model="form.description"
          type="textarea"
          placeholder="请输入角色描述"
          rows="4"
        />
      </el-form-item>
      <el-form-item label="角色状态">
        <el-switch v-model="form.status" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="changeClose">取消</el-button>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped></style>
